<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.pa_id ? '编辑' : '添加'" v-model="visible" align-center width="600px" :z-index="2000"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :label-width="140">
      <el-form-item label="部门" prop="department_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-select v-model="form.department_id" class="w-full" placeholder="请选择" @change="depChange">
          <el-option v-for="(d, i) in options.department" :key="i" :label="d.label" :value="d.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="month" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-date-picker v-model="form.month" type="month" value-format="YYYY-MM" placeholder="月份" class="w-full" />
      </el-form-item>
      <el-form-item label="金额" prop="amount" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
        <el-input-number v-model="form.amount" controls-position="right" :min="0" :step="0.01" :precision="2"
          class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick, reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

const depChange = (val) => {
  form.value.department_name = props.options.department.find(d => d.value === val)?.label
}

// 表单处理
const formRef = ref()
const form = ref({})

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    department_id: '',
    department_name: '',
    month: '',
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  // 编辑
  if (id) {
    const res = await api.detail({ dac_id: id })
    form.value = res.data
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (formRef) => {
  if (!await formRef.validate()) return
  loadings.create = true
  api[form.value.dac_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>